<!-- Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 -->
<!-- 
* @desc:登录页面
* @fileName:Login.vue
* @author:zoujunjie
* @date:2022-4-14
!-->
<template>
  <div class="page-contaienr">
    <img class="background-left" :src="backgroudLeftUrl" />
    <img class="background-right" :src="backgroudRightUrl" />
    <div class="login-container">
      <div class="card-container">
        <img class="poster" :src="posterUrl" />
        <div>
          <img class="logo" :src="logoUrl" />
          <el-form
            ref="loginForm"
            :model="loginModel"
            :rules="rules"
            size="large"
            @keyup.enter.native="submit(loginForm)"
          >
            <el-form-item prop="username">
              <el-input
                type="text"
                class="input"
                size="large"
                v-model="loginModel.username"
              >
                <template #prefix>
                  <el-image
                    class="icon"
                    :src="iconUserUrl"
                    fit="contain"
                  ></el-image>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                type="password"
                class="input"
                size="large"
                v-model="loginModel.password"
              >
                <template #prefix>
                  <el-image
                    class="icon"
                    :src="iconLockUrl"
                    fit="contain"
                  ></el-image>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="code">
              <el-input
                type="text"
                class="input input-code"
                size="large"
                v-model="loginModel.code"
              >
                <template #prefix>
                  <el-image
                    class="icon"
                    :src="iconSecurityUrl"
                    fit="contain"
                  ></el-image>
                </template>
              </el-input>
              <lanius-image
                class="code"
                @click="refreshCodeKey()"
                :src="codeKey ? `/verify/${codeKey}` : ''"
              ></lanius-image>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                class="login-button"
                :loading="isLogining"
                @click="submit(loginForm)"
              >
                <template v-if="isLogining">登录中</template>
                <template v-else>登录</template>
              </el-button>
            </el-form-item>
          </el-form>
          <div class="error-text">{{ errorMessage }}</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import backgroudLeftUrl from "@/assets/img/login/background-left.png";
import backgroudRightUrl from "@/assets/img/login/background-right.png";
import posterUrl from "@/assets/img/login/poster.png";
import logoUrl from "@/assets/img/login/logo.png";
import iconUserUrl from "@/assets/img/login/icon-user.png";
import iconLockUrl from "@/assets/img/login/icon-lock.png";
import iconSecurityUrl from "@/assets/img/login/icon-security.png";
import { Ref, ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import type { FormInstance } from "element-plus";
import localTokenStrategy from "@/common/util/auth";
import { HttpClient } from "@/common/http";
import LaniusImage from "@/components/lanius/LaniusImage.vue";
import { createGuid } from "@/services/common/tool";
import { getMenuPermissions } from "@/services/user-permission";
import { checkPassword } from "@/services/common/tool";

interface LoginModel {
  username: String;
  password: String;
  code: String;
}

const route = useRoute();
const router = useRouter();

const http = new HttpClient();
const returnUrl: string = route.query.returnUrl
  ? route.query.returnUrl + ""
  : "/";
const loginForm = ref<FormInstance>();
const loginModel: Ref<LoginModel> = ref({
  username: "",
  password: "",
  code: "",
});

const validatePassword = (rule: any, value: any, callback: any) => {
  if (!checkPassword(value)) {
    callback(new Error("必须同时包含英文大小写、数字和特殊符号"));
  } else {
    callback();
  }
};
const rules = reactive({
  username: [
    {
      required: true,
      message: "还没有填写用户名",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "还没有填写密码",
      trigger: "blur",
    },
    { min: 6, max: 20, message: "长度为6-20位", trigger: "blur" },
    { validator: validatePassword, trigger: "blur" },
  ],
  code: [
    {
      required: true,
      message: "还没有填写验证码",
      trigger: "blur",
    },
  ],
});
const isLogining: Ref<Boolean> = ref(false);
const errorMessage: Ref<String> = ref("");
const codeKey: Ref<String> = ref("");

onMounted(() => {
  refreshCodeKey();
});

const refreshCodeKey = (): void => {
  codeKey.value = createGuid(false);
};

const submit = async (formInstance: FormInstance | undefined) => {
  errorMessage.value = "";
  if (!formInstance) return;
  await formInstance.validate((valid, fields) => {
    if (valid) {
      isLogining.value = true;
      http
        .post({
          url: `/user/login`,
          params: {
            key: codeKey.value,
          },
          data: {
            code: loginModel.value.code,
            userName: loginModel.value.username,
            password: loginModel.value.password,
          },
        })
        .then((result: any) => {
          console.log(result);
          localTokenStrategy.setToken(result.data.token);
          result.data.user.isChief = result.data.chief;
          result.data.user.isAdmin = false;
          result.data.user.organizationId = result.data.orgId;
          localTokenStrategy.setUserInfo(result.data.user);
          getMenuPermissions().then(() => {
            router.push(returnUrl);
          });
        })
        .catch((err: any) => {
          console.log("err", err);
          errorMessage.value = err?.data || "系统繁忙，请稍候重试";
          isLogining.value = false;
          refreshCodeKey();
        });
    }
  });
};
</script>
<style scoped lang="scss">
.page-contaienr {
  width: 100vw;
  height: 100vh;
  .login-container {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2;
    .poster {
      margin-right: 160px;
    }
    .card-container {
      width: 1040px;
      height: 600px;
      box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.16);
      background-color: transparent;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;

      .logo {
        margin-bottom: 20px;
      }
      .input {
        width: 260px;
        height: 38px;
      }
      .input-code {
        width: 150px;
        margin-right: 10px;
      }
      .icon {
        //width: 17px;
        height: 17px;
        //top: 12px;
      }
      .login-button {
        width: 260px;
        margin-top: 30px;
        height: 38px;
      }

      .error-text {
        color: var(--el-color-danger);
        height: 18px;
      }
      .code {
        height: 40px;
        width: 100px;
      }
      .code:hover {
        cursor: pointer;
      }
    }
  }
  .background-left {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
  }
  .background-right {
    position: absolute;
    bottom: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
